﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
using System.Text.RegularExpressions;
using System.IO.Compression;
using System.Reflection;
namespace UTIL
{
    public class CWeather
    {
        /**/
        /// <summary>
        /// 获取当天的天气情况
        /// </summary>
        /// <param name="City"></param>
        /// <returns></returns>
        public static string ThiefWeather(string City)
        {
            string TodayWeather;
            string thisDate = DateTime.Today.ToString("yyyyMMdd");           
            try
            {
                Uri uri = new Uri("http://www.baidu.com/s?wd=" +City + "天气预报" + "&cl=3");
                //String strUrl = "http://www.baidu.com/s?wd=" + City + "天气预报" + "&cl=3";
                HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create(uri);
                wreq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
                HttpWebResponse wresp = (HttpWebResponse)wreq.GetResponse();
                Stream s = wresp.GetResponseStream();
                //System.IO.StreamReader objReader = new System.IO.StreamReader(new GZipStream(s, CompressionMode.Decompress), System.Text.Encoding.GetEncoding("gbk"));
                StreamReader objReader = new StreamReader(s, System.Text.Encoding.GetEncoding("GB2312"));
                string HTML = objReader.ReadToEnd();
                TodayWeather = GetRegValue("city=" + City + "\" target=\"_blank\">" + City + "</a>(.+?)\n", HTML);
            }
            catch(Exception me)
            {
                TodayWeather = "";
                UTIL.CException.SaveExcepiton(UTIL.ErrorType.Error, me, MethodBase.GetCurrentMethod().GetType());//A-2009-10-11 
            }           
            return TodayWeather;
        }
        /**/
        /// <summary>
        /// 正则表达式获取对应数据
        /// </summary>
        /// <param name="RegexString"></param>
        /// <param name="RemoteStr"></param>
        /// <returns></returns>
        private static string GetRegValue(string RegexString, string RemoteStr)
        {
            string MatchVale = "";
            Regex r = new Regex(RegexString);
            Match m = r.Match(RemoteStr);
            if (m.Success)
            {
                MatchVale = m.Groups[1].ToString();
            }
            return MatchVale;
        }
    }
}
